<?php
namespace App\Http\Controllers\api;
use App\ChargeAvailable;
use App\Coupons;
use App\Goods;
use App\Http\Services\BusinessLicense;
use App\Http\Services\FileManager;
use App\Http\Services\ToolsManager;
use App\Http\Services\UserManager;
use App\QrCodes;
use App\Shops;
use App\User;
use App\UserAddress;
use App\UserCoupon;
use App\UserInfo;
use App\UserIntegralRecord;
use Faker\Provider\DateTime;
use Illuminate\Http\Request;

use App\Http\Requests;
use App\Http\Controllers\Controller;

class UCenterController extends Controller
{
    /**
     * 获取用户信息
     * @param Request $request
     * @return \Illuminate\Contracts\Routing\ResponseFactory|\Illuminate\Http\JsonResponse|\Symfony\Component\HttpFoundation\Response
     */
    public function getUserInfo(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        if(is_null($user->phone)){
            $user->phone = '';
        }

        /** @var UserInfo $userInfo */
        $userInfo = UserInfo::whereUserId($user->id)->first();
        if(!$userInfo)
            return response()->json(['level' => 'error','message' => '用户信息不存在']);

        $userInfo->photo_url = FileManager::getImgUrl($userInfo->photo_id);

        $user->user_info = $userInfo;
        $user->coupon_number = (string)UserCoupon::whereUserId($user->id)->whereIsUse(0)->count();
        $balance=ChargeAvailable::whereUserId($user->id)->first();
        $user->balance  = $balance ? (string)$balance->amount : '0';


        return response(['level' => 'success','message' => '获取成功','data' => $user]);
    }

    public function getDistance(Request $request){
        $lng      = !is_null($request->get('lng')) ? $request->get('lng') : 111.121017;
        $lat      = !is_null($request->get('lat')) ? $request->get('lat') : 35.505871;

        $distances = [];
        $shops = Shops::all();
        if(count($shops) > 0){
            foreach($shops as $shop){
                $distance = 0;
                $result = BusinessLicense::distanceCalculation($lng,$lat,$shop->lng,$shop->lat);
                if(!empty($result) && $result->status == 0){
                    $distance = $result->result->elements[0]->distance;
                }

                $distances[$shop->id] = $distance;
            }
        }

        $shop = null;
        if(count($distances) > 0){
            $pos = array_search(min($distances), $distances);

            $shop = Shops::whereId($pos)->first();
            if($shop){
                $shop->thumb_url = FileManager::getImgUrl($shop->thumb_id);
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $shop]);
    }
    /**
     * 新增收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function newShippingAddress(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */

        $consignee = $request->get('consignee');
        $phone     = $request->get('phone');
        $province  = $request->get('province');
        $city      = $request->get('city');
        $area      = $request->get('area');
        $addDetail = $request->get('add_detail');
        $postcode  = $request->get('postcode');
        $isDefault = !is_null($request->get('is_default')) ? $request->get('is_default') : 0;
        $id        = !is_null($request->get('id')) ? $request->get('id') : 0;

        if(is_null($consignee) || $consignee == '')
            return response()->json(['level' => 'error','message' => '请输入收件人姓名']);

        if(is_null($phone) || $phone == '' || !preg_match("/^(1[34578])[0-9]{9}$/", $phone))
            return response()->json(['level' => 'error','message' => '请正确输入收件人手机号码']);

        if(is_null($province) || $province == '')
            return response()->json(['level' => 'error','message' => '请选择所在省份']);

        if(is_null($city) || $city == '')
            return response()->json(['level' => 'error','message' => '请选择所在城市']);

        if(is_null($area) || $area == '')
            return response()->json(['level' => 'error','message' => '请选择所在地区']);

        if(is_null($addDetail) || $addDetail == '')
            return response()->json(['level' => 'error','message' => '请输入详细地址']);

//        if(is_null($postcode) || $postcode == '' || !preg_match("/^[0-9]{6}$/", $postcode))
//            return response()->json(['level' => 'error','message' => '请正确输入邮政编码']);



        /** @var UserAddress $isUserAddress */
        $isUserAddress = UserAddress::whereUserId($user->id)->whereIsDefault(1)->first();
        if($isDefault == 1 && $isUserAddress){
            $isUserAddress->is_default = 0;
            $isUserAddress->save();
        }

        $newUserAddress = UserAddress::whereId($id)->first();
        if(!$newUserAddress){
            /** @var UserAddress $selectUserAdd */
            $selectUserAddress = UserAddress::whereUserId($user->id)->get();
            if(count($selectUserAddress) > 0){
                foreach($selectUserAddress as $selectUserAdd){
                    if($selectUserAdd->consignee == $consignee && $selectUserAdd->phone == $phone && $selectUserAdd->province == $province && $selectUserAdd->city == $city && $selectUserAdd->area == $area && $selectUserAdd->add_detail == $addDetail && $selectUserAdd->postcode == $postcode)
                        return response()->json(['level' => 'error','message' => '收货地址已存在']);
                }
            }

            $newUserAddress = new UserAddress();
        }

        $newUserAddress->user_id              = $user->id;
        $newUserAddress->consignee            = $consignee;
        $newUserAddress->phone                = $phone;
        $newUserAddress->province             = $province;
        $newUserAddress->city                 = $city;
        $newUserAddress->area                 = $area;
        $newUserAddress->add_detail           = $addDetail;
        $newUserAddress->postcode             = $postcode;
        $newUserAddress->is_default           = $isDefault;
        $newUserAddress->save();

        return response()->json(['level' => 'success','message' => '设置收货地址成功','data' => $newUserAddress]);
    }

    /**
     * 获取收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getShippingAddress(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        if($id != '' && $id != 0){
            $userAddress = UserAddress::whereId($id)->whereUserId($user->id)->get();
        }else{
            $userAddress = UserAddress::whereUserId($user->id)->get();
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userAddress]);
    }

    /**
     * 删除收货地址
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     * @throws \Exception
     */
    public function deleteShippingAddress(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /* if(is_null($user->phone) || $user->phone == '')
           return response()->json(['level' => 'error','message' => '请绑定手机号','data' => 'no_binding']); */

        $id = !is_null($request->get('id')) ? $request->get('id') : 0;

        /** @var UserAddress $userAddress */
        $userAddress = UserAddress::whereId($id)->first();
        if(!$userAddress)
            return response()->json(['level' => 'error','message' => '该收货地址不存在']);

        if($userAddress->is_default == 1){
            /** @var UserAddress $newestUserAddress */
            $newestUserAddress = UserAddress::whereUserId($user->id)->orderBy('created_at','desc')->first();
            if($newestUserAddress){
                $newestUserAddress->is_default = 1;
                $newestUserAddress->save();
            }
        }


        $userAddress->delete();


        return response()->json(['level' => 'success','message' => '删除成功','data' => $userAddress]);
    }
    public function getUserIntegralList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $userIntegralList = UserIntegralRecord::whereUserId($user->id)->get();
        if(count($userIntegralList) > 0){
            foreach($userIntegralList as $userIntegral){
                $thisGoods = Goods::whereId($userIntegral->goods_id)->first();
                if($thisGoods){
                    $thisGoods->thumb_url = FileManager::getImgUrl($thisGoods->thumb_id);
                }

                $userIntegral->goods_info = $thisGoods ? $thisGoods :null;
            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userIntegralList]);
    }

    /**
     * 优惠券列表
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getCouponList(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        /** @var Coupons $coupon */
        $coupons = Coupons::whereStatus(1)->orderBy('created_at','desc')->get();
        if(count($coupons) > 0){
            foreach($coupons as $coupon){
                if($user){
                    $userCoupon = UserCoupon::whereUserId($user->id)->whereCouponId($coupon->id)->first();
                    if($userCoupon){
                        $coupon->is_receive = 'yes';
                    }else{
                        $coupon->is_receive = 'no';
                    }
                } else {
                    $coupon->is_receive = 'no';
                }
                if ($coupon->img_id)
                    $coupon->img_url=FileManager::getImgUrl($coupon->img_id);
                else
                    $coupon->img_url=false;

            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $coupons]);
    }

    public  function  getHomeCoupon(Request $request){



        /** @var Coupons $coupon */
        $coupons = Coupons::whereStatus(1)->whereRemark('home')->orderBy('created_at','desc')->get();
        if(count($coupons) > 0){
            foreach($coupons as $coupon){


                $coupon->img_url=FileManager::getImgUrl($coupon->img_id);

                if($coupon->type=="direct"){
                    $coupon->coupon_type="无门槛优惠券";
                }

                if($coupon->type=="satisfy"){
                    $coupon->coupon_type="满减优惠券";
                }

            }
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $coupons]);

    }

    public  function  getCouponDetail(Request $request){


        $coupon_id=!is_null($request->get('coupon_id'))?$request->get('coupon_id'):0;
        $user = UserManager::isLogin($request);
        if(!$user){

            $coupon=Coupons::whereId($coupon_id)->whereStatus(1)->first();

            $coupon->img_url=FileManager::getImgUrl($coupon->img_id);


            if($coupon->type=="direct"){
                $coupon->coupon_type="无门槛优惠券";
            }

            if($coupon->type=="satisfy"){
                $coupon->coupon_type="满减优惠券";
            }

        }else{


            $coupon=Coupons::whereId($coupon_id)->whereStatus(1)->first();
            if(!$coupon)
                return response()->json(['level' => 'error','message' => '找不到优惠券信息']);

            $userCoupon = UserCoupon::whereUserId($user->id)->whereCouponId($coupon->id)->first();

            if($coupon->type=="direct"){
                $coupon->coupon_type="无门槛优惠券";
            }

            if($coupon->type=="satisfy"){
                $coupon->coupon_type="满减优惠券";
            }

            $coupon->img_url=FileManager::getImgUrl($coupon->img_id);


            if($userCoupon){
                $coupon->is_receive = 'yes';
            }else{
                $coupon->is_receive = 'no';
            }
        }


        return response()->json(['level' => 'success','message' => '获取成功','data' => $coupon]);
    }

    /**
     * 优惠券领取入口
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function couponReceive(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录！','data' => 'no_login']);

        $couponId = !is_null($request->get('coupon_id')) ? $request->get('coupon_id') : 0;

        /** @var Coupons $thisCoupon */
        $thisCoupon = Coupons::whereId($couponId)->first();
        if(!$thisCoupon)
            return response()->json(['level' => 'error','message' => '该优惠券不存在！']);

        if($thisCoupon->status == 0)
            return response()->json(['level' => 'error','message' => '系统错误']);

        if(strtotime($thisCoupon->end_time) < time())
            return response()->json(['level' => 'error','message' => '优惠券已过期']);

        $userCoupon = UserCoupon::whereUserId($user->id)->whereCouponId($thisCoupon->id)->first();
        if($userCoupon)
            return response()->json(['level' => 'error','message' => '您已经领取过了']);

        if($thisCoupon->num==0)
            return response()->json(['level' => 'error','message' => '优惠券已经领取完，下次再来']);
        $thisCoupon->num=$thisCoupon->num-1;
        $thisCoupon->save();

        $newUserCoupon = new UserCoupon();
        $newUserCoupon->user_id       = $user->id;
        $newUserCoupon->coupon_id     = $thisCoupon->id;
        $newUserCoupon->name          = $thisCoupon->name;
        $newUserCoupon->money         = $thisCoupon->money;
        $newUserCoupon->type          = $thisCoupon->type;
        $newUserCoupon->satisfy_money = $thisCoupon->satisfy_money;
        $newUserCoupon->start_time    = $thisCoupon->start_time;
        $newUserCoupon->end_time      = $thisCoupon->end_time;
        $newUserCoupon->save();

        return response()->json(['level' => 'success','message' => '领取成功','data' => $newUserCoupon]);
    }

    /**
     * 获取我的优惠券
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function getUserCoupon(Request $request){
        /** @var User $user */
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $type = !is_null($request->get('type')) && $request->get('type') != '' ? $request->get('type') : 'ha';


        if($type == 'unused'){
            $userCoupon = UserCoupon::whereUserId($user->id)->whereIsUse(0)->whereIsLocking(0)->where('end_time','>', date('Y-m-d H:i:s',time()))->get();
        }elseif($type == 'used'){
            $userCoupon = UserCoupon::whereUserId($user->id)->whereIsUse(1)->get();
        }elseif($type == 'expired'){
            $userCoupon = UserCoupon::whereUserId($user->id)->where('end_time','<=', date('Y-m-d H:i:s',time()))->get();
        }else{
            $userCoupon = UserCoupon::whereUserId($user->id)->get();
        }

        return response()->json(['level' => 'success','message' => '获取成功','data' => $userCoupon]);
    }

    public  function scanningIntegral(Request $request){

        $qrcode_key=$request->get('qrcode_key');
        $url=$request->get('url');
        $user = UserManager::isLogin($request);
        if(!$user)
            return response()->json(['level' => 'error','message' => '请先登录!','data' => 'no_login']);

        $qrcode=QrCodes::whereQKey($qrcode_key)->whereUrl($url)->first();

        if(!$qrcode)
            return response()->json(['level' => 'error','message' => '抱歉，没有找到数据!','data'=>'no_data']);

        if($qrcode->is_use==1)
            return response()->json(['level' => 'error','message' => '抱歉，二维码扫已被扫描过!','data'=>'is_use']);

        /*      if($qrcode->status==1)
                  return response()->json(['level' => 'error','message' => '抱歉，二维码已经失效!','data'=>'is_invalid']);*/
        $userInfo=UserInfo::whereUserId($user->id)->first();
        if(!$userInfo)
            return response()->json(['level' => 'error','message' => '用户信息出错!','data'=>'no_user_info']);

        $qrcode->is_use=1;
        $qrcode->use_time=date('Y-m-d h:m:s');
        $qrcode->save();

        $userInfo->integral=$userInfo->integral + $qrcode->integral;
        $userInfo->save();

        $newUserIntegralRecord=new UserIntegralRecord();
        $newUserIntegralRecord->integral=$qrcode->integral;
        $newUserIntegralRecord->type="scanning";
        $newUserIntegralRecord->user_id=$user->id;
        $newUserIntegralRecord->save();

        $data['get_integral']="恭喜您获得".$qrcode->integral."积分";
        $data['integral']=$qrcode->integral;

        return response()->json(['level' => 'success','message' => '获取成功','data' =>$data]);
    }

}
